package com.study.zookeeper.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Service
public class CurdActionService {

    private static final Logger logger = LoggerFactory.getLogger(CurdActionService.class);

    @Autowired
    private CuratorFramework curatorClient;

    public void create() {
        //创建一个空节点
        try {
            curatorClient.create().forPath("/root-node");
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //创建一个有数据的节点
        try {
            curatorClient.create().forPath("/wufaliang", "you are super men".getBytes());
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //创建一个临时的有数据节点
        try{
            System.out.println("-------liuxia------");
            curatorClient.create().withMode(CreateMode.EPHEMERAL).forPath("/liuxia", "hello world".getBytes());
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //创建一个永久的有数据节点
        try{
            curatorClient.create().withMode(CreateMode.PERSISTENT).forPath("/babao", "baby".getBytes());
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //创建一个带有版本号的数据节点
        try{
            curatorClient.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/haha", "baby".getBytes());
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //创建一个临时节点，并递归创建父节点，带有内容
        //创建一个临时的有数据节点
        try{
            curatorClient.create().creatingParentContainersIfNeeded().
                    withMode(CreateMode.PERSISTENT).forPath("/home/flwu", "women".getBytes());
            curatorClient.create().creatingParentContainersIfNeeded().
                    withMode(CreateMode.PERSISTENT).forPath("/home/flwu1", "women".getBytes());
            curatorClient.create().creatingParentContainersIfNeeded().
                    withMode(CreateMode.PERSISTENT).forPath("/home/flwu2", "women".getBytes());
            logger.info("success");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void update() {
        try {
            curatorClient.setData().forPath("/wufaliang", "update wufaliang".getBytes());
            logger.info("update行为执行完成");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //带版本更新
        try{
            curatorClient.setData().withVersion(10086).forPath("/wufaliang", "you are version content".getBytes());
            logger.info("带版本更新完成");
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void delete() {
        try {
            curatorClient.delete().forPath("/wufaliang");
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
        //删除
        try {
            curatorClient.delete().forPath("/home/flwu");
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
        //递归删除所有子节点
        try {
            curatorClient.delete().deletingChildrenIfNeeded().forPath("/home/flwu1");
        }catch (Exception e) {}

        //带版本删除
        try {
            curatorClient.delete().withVersion(10086).forPath("/home/babao");
        }catch (Exception e) {}

        //删除一个节点，强制保证删除，（重试机制）
        try{
            curatorClient.delete().guaranteed().forPath("/root-node");
        } catch (Exception e) {}
    }

    public void get() {
        try {
            byte[] data = curatorClient.getData().forPath("/babao");
            String aa = new String(data);
            logger.info("内容为：" + aa);
        }catch (Exception e) {
            System.out.print(e.getMessage());
        }
        //读取内容，并获取状态
        try {
            Stat stat = new Stat();
            byte[] data = curatorClient.getData().storingStatIn(stat).forPath("/babao");
            String aa = new String(data);
            logger.info("内容为：" + aa);
            logger.info("版本为：" + stat.getVersion());
            logger.info("创建时间：" + stat.getCtime());
        }catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }

    public void isExist() {
        try {
            Stat stat = curatorClient.checkExists().forPath("/babao");
            System.out.print(String.valueOf(stat.getVersion()));
        } catch (Exception e) {
            System.out.println("接单已经不存在了");
        }

    }

    public void getAllChildren() {
        try {
            List<String> path =  curatorClient.getChildren().forPath("/home");
            for(String pathName : path) {
                System.out.print(pathName);
            }
        } catch (Exception e) {

        }
    }

    public void yibuCreate() {
        try {
            //使用独立的线程池，异步执行
            Executor executor = Executors.newFixedThreadPool(2);
            curatorClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT)
                    .inBackground((curatorFramework, curatorEvent) -> {
                        System.out.println(curatorEvent.getType());
                        System.out.println(curatorEvent.getResultCode());
                        Thread.sleep(2000);
                    }, executor).forPath("/home/wufaliang/liuxia");
            System.out.println("吴发亮");
        } catch (Exception e) {

        }

    }

    /**
     * 事务处理  新版本已经不支持了
     */
    public void transaction() {

    }
}
